import React, {Component} from 'react';
import {Button, Form, Input, Message} from 'semantic-ui-react';
import '../style/login.scss';
import {Link} from 'react-router-dom';
import {createForm, formShape} from 'rc-form';
import _ from 'lodash';

class Login extends Component {
    static propTypes = {
        form: formShape
    };

    state = {
        errMsg: null
    };

    handleDismiss() {
        this.setState({errMsg: null});
    }

    renderError() {
        if (this.state.errMsg) {
            return (
                <Message negative onDismiss={() => this.handleDismiss()}>
                    {this.state.errMsg}
                </Message>
            );
        }
    }

    onSubmit = () => {
        const {form} = this.props;
        form.validateFields((error, value) => {
            if (error) {
                const errMsg = _.values(error)[0].errors[0].message;
                this.setState({
                    errMsg
                });
                return;
            }
            this.doSubmit(value);
        })
    };

    doSubmit(value) {
        //TODO:
    }

    render() {
        const {getFieldProps, getFieldDecorator} = this.props.form;
        const accountProps = getFieldProps('account', {
            initialValue: '',
            rules: [
                {required: true, message: '请输入手机号或邮箱'}
            ]
        });
        const passwordDecorator = getFieldDecorator('password', {
            initialValue: '',
            rules: [
                {required: true, message: '请输入密码'},
                {len: 5, message: '密码长度为5位'}
            ]
        });
        return (
            <div className="page-login">
                <div className="form-wrapper">
                    {this.renderError()}
                    <Form className="auth-form" onSubmit={this.onSubmit}>
                        <h3 className="auth-form__head">登&emsp;录</h3>
                        <div className="auth-form__body">
                            <Form.Field>
                                <label>手机号或邮箱</label>
                                <Input {...accountProps}/>
                            </Form.Field>
                            <Form.Field>
                                <label>忘记密码
                                    <Link className="right"
                                          to="forgot-pwd">忘记密码?</Link>
                                </label>
                                {passwordDecorator(<Input/>)}
                            </Form.Field>
                            <p className="auth-tips">没有账户?
                                <Link to="register">立即注册</Link>
                            </p>
                            <Button fluid type="submit" primary
                                    size="large">登录</Button>
                        </div>
                    </Form>
                </div>
            </div>
        );
    }
}

export default createForm()(Login);